package com.fire.component.utils.time;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class DateUtils {

    public static final String YYYYMMDD = "yyyyMMdd";

    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static final String HHMMSS = "HHmmss";

    public static final String HH_MM_SS = "HH:mm:ss";

    /**
     * 日期解析
     *
     * @param dateString
     * @param pattern
     * @return
     */
    public static Date parse(String dateString, String pattern) {
        if (StringUtils.isEmpty(dateString)) {
            throw new RuntimeException("parsing date error, dateString is null!");
        }
        if (StringUtils.isEmpty(pattern)) {
            throw new RuntimeException("parsing date error, pattern is null!");
        }
        DateFormat df = new SimpleDateFormat(pattern);
        try {
            return df.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 日期格式化
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        if (date == null) {
            throw new RuntimeException("format date error, date value is null");
        }
        if (StringUtils.isEmpty(pattern)) {
            throw new RuntimeException("format date error, pattern is null");
        }
        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(date);
    }

    public static long getTimeStamp() {
        return Long.parseLong(format(new Date(), "yyyyMMddHHmmssSSS"));
    }


    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getNowDate() {
        return getNow(YYYYMMDD);
    }

    /**
     * 获取当前自定义格式日期
     *
     * @param pattern
     * @return
     */
    public static String getNow(String pattern) {
        Date date = new Date();
        return format(date, pattern);
    }

    /**
     * 获取当前时间字符串
     *
     * @return
     */
    public static String getNowTime() {
        return getNow(HHMMSS);
    }

    /**
     * 日期增加指定单位的时间
     *
     * @param date
     * @param count
     * @param timeUnit
     */
    public static Date incrementTime(Date date, int count, TimeUnits timeUnit) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        switch (timeUnit) {
            case MILLSECONDS:
                gc.add(GregorianCalendar.MILLISECOND, count);
                return gc.getTime();
            case SECONDS:
                gc.add(GregorianCalendar.SECOND, count);
                return gc.getTime();
            case MINUTES:
                gc.add(GregorianCalendar.MINUTE, count);
                return gc.getTime();
            case HOURS:
                gc.add(GregorianCalendar.HOUR, count);
                return gc.getTime();
            case DAYS:
                gc.add(GregorianCalendar.DAY_OF_MONTH, count);
                return gc.getTime();
            case WEEKS:
                gc.add(GregorianCalendar.WEEK_OF_MONTH, count);
                return gc.getTime();
            case MONTHS:
                gc.add(GregorianCalendar.MONTH, count);
                return gc.getTime();
            case SEASON:
                gc.add(GregorianCalendar.MONTH, 3);
                return gc.getTime();
            case YEAR:
                gc.add(GregorianCalendar.YEAR, count);
                return gc.getTime();
            default:
                return date;
        }
    }

    /**
     * 日期减少指定单位的时间
     *
     * @param date
     * @param count
     * @param timeUnit
     */
    public static Date decrementTime(Date date, int count, TimeUnits timeUnit) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        switch (timeUnit) {
            case MILLSECONDS:
                gc.add(GregorianCalendar.MILLISECOND, -count);
                return gc.getTime();
            case SECONDS:
                gc.add(GregorianCalendar.SECOND, -count);
                return gc.getTime();
            case MINUTES:
                gc.add(GregorianCalendar.MINUTE, -count);
                return gc.getTime();
            case HOURS:
                gc.add(GregorianCalendar.HOUR, -count);
                return gc.getTime();
            case DAYS:
                gc.add(GregorianCalendar.DAY_OF_MONTH, -count);
                return gc.getTime();
            case WEEKS:
                gc.add(GregorianCalendar.WEEK_OF_MONTH, -count);
                return gc.getTime();
            case MONTHS:
                gc.add(GregorianCalendar.MONTH, -count);
                return gc.getTime();
            case SEASON:
                gc.add(GregorianCalendar.MONTH, 3);
                return gc.getTime();
            case YEAR:
                gc.add(GregorianCalendar.YEAR, -count);
                return gc.getTime();
            default:
                return date;
        }
    }

    /**
     * 获取当前时间。 <br>
     * 获取的时间的格式为6位(HHmmss)或5位(Hmmss)
     *
     * @return String - 返回当前时间
     */
    public static String getTime() {
        SimpleDateFormat dataFormat = new SimpleDateFormat("HHmmss");
        Date date = new Date();
        String timeString = dataFormat.format(date);
        return timeString;
    }

    /**
     * 计算两个日期相隔天数。 <br>
     * 计算结果统一成正数
     *
     * @param date1 - 指定日期(yyyyMMdd)的其中一个
     * @param date2 - 指定日期(yyyyMMdd)的另外一个
     * @return int - 返回计算后的天数 失败返回-1
     */
    public static int diffDate(String date1, String date2) {
        try {
            SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
            Date d1 = simpledateformat.parse(date1);
            Date d2 = simpledateformat.parse(date2);
            long tmp = d1.getTime() - d2.getTime();
            if (tmp < 0) {
                tmp = -tmp;
            }
            int diff = (int) (tmp / (24 * 60 * 60 * 1000));
            return diff;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static int diffDate(Date date1, Date date2) {
        try {

            long tmp = date1.getTime() - date2.getTime();
            if (tmp < 0) {
                tmp = -tmp;
            }
            int diff = (int) (tmp / (24 * 60 * 60 * 1000));
            return diff;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 获取当前时间，格式为yyyyMMdd
     *
     * @param date
     * @return
     */
    public static String getDateStr(Date date) {
        return format(date, "yyyyMMdd");
    }

    /**
     * 计算某日期+- N天的日期
     *
     * @param theDateStr
     * @param days
     * @return
     */
    public static String getDateStr(String theDateStr, int days) {
        boolean is8 = theDateStr.length() == 8;
        String dateStr = is8 ? format(theDateStr) : theDateStr;
        Date theDate = java.sql.Date.valueOf(dateStr);
        return is8 ? dateTo8(getDateStr(theDate, days)) : getDateStr(theDate, days);
    }

    /**
     * 计算某日期+- N天的日期
     *
     * @param theDate
     * @param days
     * @return
     */
    public static String getDateStr(Date theDate, int days) {
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(theDate);
        c.add(GregorianCalendar.DATE, days);
        java.sql.Date d = new java.sql.Date(c.getTime().getTime());
        return d.toString();
    }

    /**
     * 日期格式化。 <br>
     * 10位yyyy/MM/dd 转换为8位yyyyMMdd
     *
     * @param date - 要格式化的日期字符串: 10位 yyyy/MM/dd或yyyy-MM-dd
     * @return String - 返回格式化后的日期 <br>
     * 若date长度不为10，即格式不为yyyy/MM/dd形式的日期，则直接返回date。 <br>
     * 若date为null, 则返回""
     */
    public static String dateTo8(String date) {
        if (date == null) {
            return "";
        }
        if (date.trim().length() != 10) {
            return date;
        }
        return date.substring(0, 4).concat(date.substring(5, 7).concat(date.substring(8, 10)));
    }

    /**
     * 将yyyyMMdd字符串格式化为yyyy-MM-dd <br>
     * Excel导出需要 <br>
     * Add by chenzhen09567
     *
     * @param source yyyyMMdd 格式的字符串
     * @return yyyy-MM-dd 格式的字符串
     */
    public static String format(String source) {
        return format(source, "-");
    }

    /**
     * 将yyyyMMdd字符串格式化为10位的格式
     *
     * @param source yyyyMMdd 格式的字符串
     * @param split  分隔号
     * @return yyyy-MM-dd 、yyyy/MM/dd 等格式的字符串
     */
    public static String format(String source, String split) {
        if (null != source && source.trim().length() == 8) {
            return source.substring(0, 4).concat(split).concat(source.substring(4, 6)).concat(split).concat(source.substring(6));
        }
        return source;
    }

    public static void main(String[] args) {
        //		System.out.println(parse("20171122", YYYYMMDD));
        //		System.out.println(parse("2017-11-22", YYYY_MM_DD));
        //		System.out.println(parse("20171122193022 ", YYYYMMDDHHMMSS));
        //		System.out.println(parse("2017-11-22 19:32:18", YYYY_MM_DD_HH_MM_SS));
        //		System.out.println(format(new Date(), YYYYMMDD));
        //		System.out.println(format(new Date(), YYYY_MM_DD));
        //		System.out.println(format(new Date(), YYYYMMDDHHMMSS));
        //		System.out.println(format(new Date(), YYYY_MM_DD_HH_MM_SS));
        Date date = incrementTime(new Date(), 1, TimeUnits.YEAR);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.SEASON);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.MONTHS);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.WEEKS);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.DAYS);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.HOURS);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.MINUTES);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
        date = incrementTime(new Date(), 1, TimeUnits.SECONDS);
        System.out.println(format(date, YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 支持类似将9:00转换为09:00:00
     *
     * @param timeStr
     * @return String
     */
    public static String transTimeStr(String timeStr) {
        if (timeStr.length() == 2) {
            return timeStr;
        }
        String[] split = timeStr.split(":");
        if (split == null || split.length <= 0) {
            return timeStr;
        }

        String str0 = split[0];
        if (str0.length() == 1) {
            str0 = "0" + str0;
        }
        String str1 = "00";
        if (split.length > 1) {
            str1 = split[1];
            if (str1.length() == 1) {
                str1 = "0" + str1;
            }
        }
        String str2 = "00";
        if (split.length > 2) {
            str2 = split[2];
            if (str2.length() == 1) {
                str2 = "0" + str2;
            }
        }
        timeStr = str0 + ":" + str1 + ":" + str2;

        return timeStr;
    }
	/**
	 * 取当月第一天
	 *
	 * @author wlx
	 * @date 2010-8-23
	 * @version 1.0
	 */
	public static Date getCurrentMonthFirstDate(Date date) {
		Date result = date;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.set(Calendar.DAY_OF_MONTH, 1);
		result = c.getTime();
		return result;
	}
	/**
	 * 取当前年份第一天
	 *
	 * @author wlx
	 * @date 2010-8-23
	 * @version 1.0
	 */
	public static Date getCurrentYearFirstDate(Date date) {
		Date result = date;
		Calendar c = new GregorianCalendar();
		c.setTime(date);
		c.set(Calendar.DAY_OF_YEAR, 1);
		result = c.getTime();
		return result;
	}
	/**
	 * 获取当前时间，格式为yyyyMMdd
	 *
	 * @return
	 */
	public static String getDateStr() {
		return format(new Date(), "yyyyMMdd");
	}
}
